package com.future.bantang.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;

import com.future.bantang.R;
import com.future.bantang.activity.GoodThingsActivity;
import com.future.bantang.activity.GrowGrassActivity;
import com.future.bantang.activity.MainActivity;
import com.future.bantang.activity.SearchActivity;
import com.future.bantang.activity.SignActivity;
import com.future.bantang.adapter.HomeBannerPagerAdapter;
import com.future.bantang.adapter.SubFieldFragmentPagerAdapter;
import com.future.bantang.constants.BanTang;
import com.future.bantang.entity.BanTangHomeEntity;
import com.future.bantang.entity.BanTangHomeEntity.DataEntity.BannerEntity;
import com.future.bantang.eventmas.BaseEventMsg;
import com.future.bantang.utils.JsonUtils;
import com.future.bantang.utils.L;
import com.future.bantang.utils.NetUtils;
import com.future.bantang.view.BanTangScrollView;
import com.future.bantang.view.LoopViewPager;
import com.future.bantang.view.NaviView;
import com.future.bantang.view.SlidingTabLayout;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Created by Administrator on 16-1-12.
 */
public class HomeFragment extends BaseFragment {
    @ViewInject(R.id.lvp_fragment_main_head)
    private LoopViewPager mLvpBanner;
    @ViewInject(R.id.nv_fragment_main_head)
    private NaviView mNvBanner;
    @ViewInject(R.id.layout_fragment_home_body)
    private LinearLayout mLayoutBody;
    @ViewInject(R.id.stl_fragment_main_body)
    private SlidingTabLayout mSlidingTab;
    @ViewInject(R.id.vp_fragment_main_body)
    private ViewPager mVpSubFields;
    @ViewInject(R.id.fragment_home_head_hide)
    private LinearLayout mHeaderHide;
    @ViewInject(R.id.btsv_home_main)
    private BanTangScrollView mBanTangSV;

    //加载banner数据的适配器
    private HomeBannerPagerAdapter mBannerAdapter;

    private SubFieldFragmentPagerAdapter mSubFieldFragmentPagerAdapter;
    //隐藏的头部的高度
    private int mHeaderHideHeight;
    private int containorHeight = 0;

    @Subscribe(threadMode = ThreadMode.MainThread, sticky = true)
    public void setFragmentBodyHeight(MainActivity.HeightMsg msg) {
        containorHeight = msg.getArg1();
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main_layout, null);
        return view;
    }


    public class ScrollViewMsg extends BaseEventMsg<BanTangScrollView>{}



    private boolean isFirstTouch = true;
    private int mSlidingTabTop = 0;
    private int[] mSlidingTabLoc = new int[2];
    private int mHeadHideAbsBottom = 0;
    private int totalSpace = 0;
    //记录上一次点击的Y坐标
    private float lastY=0;

    @Override
    protected void initView(View view) {
        super.initView(view);
        EventBus.getDefault().register(this);
        getUIMeasureHeight();
        mSubFieldFragmentPagerAdapter = new SubFieldFragmentPagerAdapter(getChildFragmentManager());
        mVpSubFields.setAdapter(mSubFieldFragmentPagerAdapter);
        mSlidingTab.setViewPager(mVpSubFields);
        mSlidingTab.setSelectedIndicatorColors(getResources().getColor(R.color.pink));

        //将mBanTangSV传递给分栏Fragment，进一步处理事件拦截功能
        ScrollViewMsg scrollViewMsg=new ScrollViewMsg();
        scrollViewMsg.setT(mBanTangSV);
        EventBus.getDefault().postSticky(scrollViewMsg);

        //处理头部隐藏显示以及事件拦截
        mBanTangSV.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        L.d("---ACTION_DOWN---");
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float alpha=0;
                        if (isFirstTouch){
                            int mHeadHideBottom = mHeaderHide.getBottom();
                            int[] location = new int[2];
                            mHeaderHide.getLocationOnScreen(location);
                            mHeadHideAbsBottom = location[1] + mHeadHideBottom;
                            mSlidingTab.getLocationOnScreen(location);
                            totalSpace = location[1] - mHeadHideAbsBottom;
                            isFirstTouch=false;
                        }else {
                            mSlidingTab.getLocationOnScreen(mSlidingTabLoc);
                            alpha = (totalSpace - (mSlidingTabLoc[1] - mHeadHideAbsBottom)) * 1.0f / totalSpace;
                            mHeaderHide.setAlpha(alpha);
                        }
                        if (alpha==1f){
                            if (lastY==0f){
                                lastY=event.getRawY();
                            }else {
                                float rawY=event.getRawY();
                                if (rawY-lastY<0){
                                    mBanTangSV.setIsIntercept(false);
                                }else {
                                    mBanTangSV.setIsIntercept(true);
                                }
                                lastY=rawY;
                            }
                        }else {
                            mBanTangSV.setIsIntercept(true);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        lastY=0;
                        break;
                }

                return false;
            }
        });

        testMethod();
    }

    private void testMethod() {

    }


    private void setHeadAlpha(){
    }

    private boolean isHeadMeasure = false;
    private boolean isLvpMeasure = false;

    private int mLvpHeight = 0;

    /**
     * 测量部分控件高度
     */
    private void getUIMeasureHeight() {
        ViewTreeObserver viewTreeObserver = mHeaderHide.getViewTreeObserver();
        viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!isHeadMeasure) {
                    mHeaderHideHeight = mHeaderHide.getMeasuredHeight();
                    if (containorHeight > 0) {
                        //设置HomeFragment body的高度
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                                LinearLayout.LayoutParams.MATCH_PARENT
                                , containorHeight - mHeaderHideHeight);
                        mLayoutBody.setLayoutParams(params);
                    }
                    isHeadMeasure = true;
                }

                return true;
            }
        });

        ViewTreeObserver bannerViewTreeObserver = mLvpBanner.getViewTreeObserver();
        bannerViewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!isLvpMeasure) {
                    mLvpHeight = mLvpBanner.getMeasuredHeight();
                    isLvpMeasure = true;
                }
                return true;
            }
        });

    }


    //当前页索引
    private int curPage = 0;
    //每页容量
    private int pageSize = 20;

    private List<BannerEntity> bannerDatas;


    @Override
    protected void loadDatas() {
        super.loadDatas();
        RequestParams requestParams = new NetUtils.RequestParamsBuilder()
                .addPostParameter(BanTang.CLIENT_ID_KEY, BanTang.CLIENT_ID_VALUE)
                .addPostParameter(BanTang.CLIENT_SECRET_KEY, BanTang.CLIENT_SECRET_VALUE)
                .addPostParameter(BanTang.PAGE, curPage + "")
                .addPostParameter(BanTang.PAGESIZE, pageSize + "")
                .build();
        NetUtils.loadMainDatas(requestParams, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                resetDatas(responseInfo.result);
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.e("network failed", error.getMessage());
            }
        });
    }


    /**
     * 重置页面数据
     *
     * @param result
     */
    private void resetDatas(String result) {
        BanTangHomeEntity banTangHomeEntity = null;
        try {
            banTangHomeEntity = JsonUtils.perse(result, BanTangHomeEntity.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        bannerDatas = banTangHomeEntity.getData().getBanner();
        mBannerAdapter = new HomeBannerPagerAdapter(getActivity(), bannerDatas);
        mLvpBanner.setAdapter(mBannerAdapter);
        mNvBanner.setCount(bannerDatas.size());
        mNvBanner.setCurIndex(0);
        mLvpBanner.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                mNvBanner.setCurIndex(position);
                curBannerIndex = position;
            }
        });
        loopHandler.sendEmptyMessageDelayed(0, 4500);
        enableBannerLoop();
    }

    //记录当前banner的page索引
    private int curBannerIndex = 0;
    /**
     * viewpager自动循环
     */
    private Handler loopHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mLvpBanner.setCurrentItem(curBannerIndex + 1);
            if (isBannerLoop) {
                loopHandler.sendEmptyMessageDelayed(0, 4500);
            }

        }
    };

    //记录当前的banner是否开启自动循环
    private boolean isBannerLoop = false;

    //使能循环
    private void enableBannerLoop() {
        isBannerLoop = true;
    }

    //禁止循环
    private void unEnableBanaerLoop() {
        isBannerLoop = false;
    }


    /**
     * 中部分类的点击事件
     *
     * @param view
     */
    @OnClick({R.id.layout_fragment_main_goods, R.id.layout_fragment_main_search
            , R.id.layout_fragment_main_grass, R.id.layout_fragment_main_sign})
    private void onClassifySelected(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.layout_fragment_main_goods:
                intent = new Intent(getActivity(), GoodThingsActivity.class);
                break;
            case R.id.layout_fragment_main_search:
                intent = new Intent(getActivity(), SearchActivity.class);
                break;
            case R.id.layout_fragment_main_grass:
                intent = new Intent(getActivity(), GrowGrassActivity.class);
                break;
            case R.id.layout_fragment_main_sign:
                intent = new Intent(getActivity(), SignActivity.class);
                break;
        }
        if (intent != null) {
            startActivity(intent);
        }

    }


    @Override
    public void onResume() {
        super.onResume();
        //如果已完成数据加载，则使能banner循环
       /* if (bannerDatas != null) {
            enableBannerLoop();
        }
        //开启banner循环
        if (isBannerLoop) {
            loopHandler.sendEmptyMessageDelayed(0, 4500);
        }*/
    }

    @Override
    public void onPause() {
        super.onPause();
        //停止banner循环P
        //enableBannerLoop();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        loopHandler.removeCallbacksAndMessages(null);
        EventBus.getDefault().unregister(this);
    }
}
